package com.pearl.study.client.demo.lua;

import io.lettuce.core.RedisClient;
import io.lettuce.core.ScriptOutputType;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author TD
 * @version 1.0
 * @date 2024/7/25
 */
public class LuaLockTest {

    private static Integer stockCount = 100; // 商品库存数量
    private static String goodsId = "899632563356632489"; // 商品库存数量

    public static void main(String[] args) {
        // 创建客户端
        RedisClient redisClient = RedisClient.create("redis://:123456@127.0.0.1:6379/0");
        // 获取连接
        try (StatefulRedisConnection<String, String> connection = redisClient.connect()) {


            // 秒杀逻辑
            try {
                // 获取到锁
                if (RedisLockUtils.tryLock(connection.sync(), goodsId, "123456", "10")) {
                    // 减库存
                    if (stockCount > 0) {
                        stockCount = stockCount - 1;
                        System.out.println("减库存成功，剩余库存：" + stockCount);
                    } else {
                        System.out.println("库存不足");
                    }
                } else {
                    System.out.println("库存不足");
                }
            } finally {
                RedisLockUtils.unlock(connection.sync(), goodsId);
            }


        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            redisClient.shutdown();
        }
    }
}
